package compare_atomic_mutex

import (
	"fmt"
	"sync"
	"sync/atomic"
	"time"
)

func MutexAdd() {
	var a int32 = 0
	var wg sync.WaitGroup
	var mu sync.Mutex
	start := time.Now()
	for i := 0; i < 100000000; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			mu.Lock()
			a += 1
			mu.Unlock()
		}()
	}
	wg.Wait()

	spend := time.Now().Sub(start)
	timeSpendNs := spend.Nanoseconds()
	timeSpendS := spend.Seconds()
	fmt.Printf("use mutex a is %d, spend time: %d(ns),%f(s)\n", a,
		timeSpendNs, timeSpendS)
}

func AtomicAdd() {
	var a int32 = 0
	var wg sync.WaitGroup
	start := time.Now()
	for i := 0; i < 100000000; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			atomic.AddInt32(&a, 1)
		}()
	}
	wg.Wait()
	spend := time.Now().Sub(start)
	timeSpendNs := spend.Nanoseconds()
	timeSpendS := spend.Seconds()
	fmt.Printf("use atomic a is %d, spend time: %d(ns),%f(s)\n", atomic.LoadInt32(&a),
		timeSpendNs, timeSpendS)
}

//
//原文链接：https://blog.csdn.net/kevin_tech/article/details/120397992
